package com.hunk.core.auth.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hunk.core.auth.dto.UserRoleDTO;
import com.hunk.core.auth.entity.Role;
import com.hunk.core.auth.entity.User;
import com.hunk.core.auth.entity.UserRole;
import com.hunk.core.auth.repository.UserRoleRepository;
import com.hunk.core.auth.service.UserRoleService;

@Service("userRoleService")
public class UserRoleServiceImpl implements UserRoleService {

	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
    private UserRoleRepository userRoleRepository;	//注入UserRoleRepository
	
	
	@Override
	@Transactional
	public void save(UserRoleDTO userRoleDTO) {
		List<UserRole> userroles = userRoleRepository.getUserRolesByUserId(userRoleDTO.getUser().getId());
		userRoleRepository.delete(userroles);
		
		Set<UserRole> userRoles = userRoleDTO.gen();
		for (UserRole ur : userRoles) {
			userRoleRepository.save(ur);
		}
	}

	@Override
	@Transactional(readOnly=true)
	public List<UserRole> findUserRolesByUserid(String userid) {
		List<UserRole> list = new ArrayList<UserRole>();
		for (UserRole ur : userRoleRepository.getUserRolesByUserId(userid)) {
			UserRole userRole = new UserRole();
			userRole.setId(ur.getId());
			
			User user = new User();
			user.setId(ur.getUser().getId());
			userRole.setUser(user);
			
			Role role = new Role();
			role.setId(ur.getRole().getId());
			userRole.setRole(role);
			
			list.add(userRole);
		}
		return list;
	}

}
